package org.rcy.ruicingmarket.sender.email;

import org.rcy.framework.api.email.EmailSender;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @author 吴康桥
 * @Description qq邮件服务
 * @date 2022/12/7 9:50
 */

@Component
public class QQEmailSender implements EmailSender {

	@Value("${email.qq.host}")
	private String host;
	@Value("${email.qq.account}")
	private String account;
	@Value("${email.qq.key}")
	private String key;
	private  Properties props;

	@PostConstruct
	public void init() {
		props = new Properties();
		props.setProperty("mail.transport.protocol", "SMTP");

		//设置发送邮件的服务器
		props.setProperty("mail.host", host);
		props.setProperty("mail.smtp.auth", "true");// 指定验证为true

	}

	@Override
	public void send(String target,String title,String context,String contentType) throws MessagingException {
		// 创建验证器
		Authenticator auth = new Authenticator() {
			@Override
			public PasswordAuthentication getPasswordAuthentication() {
				//设置发送人的帐号和密码      帐号		   授权码
				return new PasswordAuthentication(account, key);
			}
		};
		//会话
		Session session = Session.getInstance(props, auth);

		// 2.创建一个Message，它相当于是邮件内容
		Message message = new MimeMessage(session);

		//设置发送者
		message.setFrom(new InternetAddress(account));

		//设置发送方式与接收者
		message.setRecipient(Message.RecipientType.TO, new InternetAddress(target));

		//设置邮件主题
		message.setSubject(title);
//         message.setText("这是一封激活邮件，请<a href='#'>点击</a>");

		//设置邮件内容
		message.setContent(context,contentType);

		// 3.创建 Transport用于将邮件发送
		Transport.send(message);
	}

}
